<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="600px"
    style="width: 600px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item prop="label" label="动作名称">
            <TextInput v-model="formData.label" label="动作名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="value" label="动作ID">
            <TextInput v-model="formData.value" label="动作ID" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  row: {
    type: Object,
    default: () => {}
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() => (props.type === 'add' ? '动作新建' : '动作修改'))

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  label: '',
  value: ''
})
const rules = ref({
  label: g_rules.selectRule('动作名称'),
  value: g_rules.commonInputText('动作ID')
})

onMounted(() => {
  if (props.type === 'edit') {
    g_utils.assignFormData(formData.value, props.row)
    console.log('formData.value', formData.value)
  }
})

const handleClose = _ => {
  dialogVisible.value = false
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    emit(props.type === 'add' ? 'add' : 'update', formData.value)
    handleClose()
  })
}
</script>

<style scoped lang="scss"></style>
